var keyboard;
var server = false;
var t1, t2, messages = [];
var renderLag = 150;
var lfi = 1;

Game = function(state, view, groundMap, time) {
    this.state = state;
    this.view = view;
    this.groundMap = groundMap;
    this.time = time;
};

var gameloop = function(game) {
    //    handleInput(game.state);
    updateView(game.view);

    var renderNow = Date.now() - renderLag;
    var i = messages.length - 1, v, fv, uv, rv, a;
    while (i > 0) {
	if (messages[i].t > renderNow &&
	    messages[i-1].t < renderNow) {
	    a = ( renderNow - messages[i - 1].t ) / (messages[i].t - messages[i - 1].t);
	    v = lerp(messages[i - 1].state[0].cv, messages[i].state[0].cv, a );
	    fv = lerp(messages[i - 1].state[0].fv, messages[i].state[0].fv, a );
	    uv = lerp(messages[i - 1].state[0].uv, messages[i].state[0].uv, a );
	    rv = lerp(messages[i - 1].state[0].rv, messages[i].state[0].rv, a );
	//    if (messages[i].id != lfi) {
	//	console.log(messages)
	//    }
	    break;
	}
	i--;
    }
    // (C|Sh)ould be a circular buffer :)
//    while (messages[0].t < renderNow)
//	messages.splice(0, 1);
    if (v) {
	game.state.entities[0].centerVec = Vec(v.x, v.y, v.z);
	game.state.entities[0].forwardVec = Vec(fv.x, fv.y, fv.z);
	game.state.entities[0].upVec = Vec(uv.x, uv.y, uv.z);
	game.state.entities[0].rightVec = Vec(rv.x, rv.y, rv.z);
	updateView(game.view);
    }
    
    requestAnimationFrame( function() {gameloop(game); } );
};

function lerp(v1, v2, a) {
    return Vec((1 - a) * v1.x + a * v2.x,
	       (1 - a) * v1.y + a * v2.y,
	       (1 - a) * v1.z + a * v2.z);
};

var main = function() {
    keyboard = new THREEx.KeyboardState();
    var heightmap = new HeightMap(200, 10);

    var view = initView(heightmap);
    
    // Playing around with two objects

    var car = new SlaveCar();
    view.add( new SlaveView(car) );

    var state = new State();
    state.add(car);

    game = new Game(state, view, heightmap, new Time());
    gameloop(game);


    // Playing around with server connection

    var ws = new WebSocket('ws://localhost:4444');

    ws.onopen = function() {
        game.socket = ws;
        console.log('Connected');
    };
    
    ws.onmessage = function(msg) {
        var m = JSON.parse(msg.data);
	if (m.m === 'init') {
            fi = m.frameInfo;
            game.time.setFromInfo(fi);
        } else if (m.m === 'st') {
	    messages.push(m);
	}
    };

    ws.onclose = function() {
        console.log('Connection was closed');
    };

    ws.onerror = function() {
        console.log('onerror was called');
    };
};

$(document).ready(main);
